<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog"
      :custom-class="'panna-panna-dialog_medium'"
      :append-to-body="true"
      :title="title"
      align="left"
      :close-on-click-modal="false"
      :visible.sync="innerDialogFormVisible"
      :before-close="closeDialog"
    >
      <el-form
        ref="formData"
        class="system-user-form"
        label-width="100px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          :label="sysBusinessReportTemplate.reportName"
          :label-width="formLabelWidth"
          prop="name"
          :error="errorMsg.name"
        >
          <el-input v-model="formData.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item
          :label="sysBusinessReportTemplate.applicationType"
          :label-width="formLabelWidth"
          prop="tpye"
          :error="errorMsg.tpye"
        >
          <el-radio-group v-model="formData.tpye">
            <el-radio
              v-for="(item, index) in reportTamplateType"
              :key="index"
              :label="item.value"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
          <!-- <el-input v-model="formData.tpye" autocomplete="off"></el-input> -->
        </el-form-item>
        <el-form-item
          :label="sysBusinessReportTemplate.applicationScope"
          :label-width="formLabelWidth"
          prop="scopeList"
          :error="errorMsg.scopeList"
        >
          <el-checkbox-group
            v-if="show"
            v-model="formData.scopeList"
            @change="ckChange"
          >
            <el-checkbox
              v-for="(item, index) in reportTypeList"
              :key="index"
              :label="item.value"
            >
              {{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>

        <el-form-item
          :label="sysBusinessReportTemplate.applicationNumberType"
          :label-width="formLabelWidth"
          prop="reportNumType"
          :error="errorMsg.introduction"
        >
          <el-radio-group v-model="formData.reportNumType">
            <el-radio
              v-for="(item, index) in reportNumTypeOptions"
              :key="index"
              :label="Number(item.value)"
            >
              {{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          :label="sysBusinessReportTemplate.applicationSampleCategory"
          :label-width="formLabelWidth"
          prop="sampleCategoryIdList"
          :error="errorMsg.introduction"
        >
          <el-select
            v-model="formData.sampleCategoryIdList"
            multiple
            :placeholder="operateType.pleaseSelect"
          >
            <el-option
              v-for="item in sampleCategoryOptions"
              :key="item.id"
              :label="item.sampleCategoryName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          :label="sysBusinessReportTemplate.briefIntroduction"
          :label-width="formLabelWidth"
          prop="introduction"
          :error="errorMsg.introduction"
        >
          <el-input
            v-model="formData.introduction"
            type="textarea"
            :rows="2"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="sysBusinessReportTemplate.attachmentTemplate"
          :label-width="formLabelWidth"
          prop="attachmentTemplate"
          :error="errorMsg.attachmentTemplate"
        >
          <BaseUploadFile
            v-model="formData.attachmentTemplate"
            business-type="80"
            :multiple="false"
            :limit="1"
          ></BaseUploadFile>
        </el-form-item>
      </el-form>
      <template>
        <p style="font-size: 18px">
          {{ sysBusinessReportTemplate.reportApprovalProcess }}
        </p>
        <el-table :data="tableData" fit highlight-current-row>
          <el-table-column :label="sysBusinessReportTemplate.nodeName">
            <template slot-scope="scope">
              {{ scope.row.flowNodeName }}
            </template>
          </el-table-column>
          <el-table-column :label="sysBusinessReportTemplate.nodeOrder">
            <template slot-scope="scope">
              {{ scope.row.flowCurrentNode }}
            </template>
          </el-table-column>
          <el-table-column :label="sysBusinessReportTemplate.userGroup">
            <template slot-scope="scope">
              <el-select v-model="scope.row.flowNodeGroup" disabled>
                <el-option
                  v-for="(item, index) in groupList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column :label="sysBusinessReportTemplate.nodeLabel">
            <template slot-scope="scope">
              {{ "{" + scope.row.flowNodeName + "}" }}
            </template>
          </el-table-column>
        </el-table>
      </template>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button
          type="primary"
          :disabled="!submitLoad"
          @click="onSubmit('formData')"
          >{{ operateType.save }}</el-button
        >
        <el-button @click="closeDialog">{{ operateType.cancel }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  create,
  update,
  get,
} from "../../../api/SysBusiness/SysBusinessReportTemplate";
import { SampleCategoryParentGetList } from "../../../api/DetectionItemManage/SysBusinessSampleCategory";
import { ReportTamplateType } from "../../../utils/dictionary";
import { GetUserGroupList } from "../../../api/Permission/PermissionUserGroup.js";
import { getDictList } from "../../../api/System/SystemDict";
import { GetWorkFlowDetailList } from "../../../api/WorkFlow/WorkFlow.js";
import _ from "lodash";

export default {
  name: "SysBusinessReportTemplateEdit",
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },

    editId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      submitLoad: true,
      show: true,
      reportNumTypeOptions: [],
      sampleCategoryOptions: [],
      title: "",
      loading: false,
      innerDialogFormVisible: false,
      formLabelWidth: "120px",
      initData: {
        id: "",
        name: "",
        introduction: "",
        tpye: "SingleSample",
        scope: [],
        attachmentTemplate: [],
        attachmentName: "",
        scopeList: [],
      },
      formData: {
        sampleCategoryIdList: [],
        id: "",
        name: "",
        introduction: "",
        tpye: "SingleSample",
        scope: [],
        attachmentTemplate: [],
        attachmentName: "",
        reportNumType: "",
        scopeList: [],
      },
      formDataRules: {
        reportNumType: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        sampleCategoryIdList: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        name: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],

        tpye: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        scopeList: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateArrayFunction,
          },
        ],
      },
      initErrorMsg: {
        name: "",
        introduction: "",
        tpye: "",
        scope: "",
        scopeList: "",
        attachmentTemplate: "",
        creator: "",
        updater: "",
      },
      errorMsg: {
        name: "",
        introduction: "",
        tpye: "",
        scope: "",
        scopeList: "",
        attachmentTemplate: "",
        creator: "",
        updater: "",
      },
      reportTypeList: [],
      tableData: [],
      groupList: [],
    };
  },
  computed: {
    reportTamplateType() {
      const arr = [];
      for (const i in ReportTamplateType) {
        arr.push({
          label: ReportTamplateType[i].label,
          value: ReportTamplateType[i].value,
        });
      }
      return arr;
    },
    operateType() {
      return this.$t("ModuleSysBusiness.OperateType") || {};
    },
    sysBusinessReportTemplate() {
      return this.$t("SysBusinessReportTemplate") || {};
    },
  },
  watch: {
    dialogFormVisible(val) {
      this.innerDialogFormVisible = val;
      if (val) {
        this.init();
      }
    },
    innerDialogFormVisible(val) {
      this.$emit("update:dialogFormVisible", val);
    },
    editId: {
      handler() {
        if (this.editId) {
          this.init();
        }
    getDictList({ dictCode: "ReportType" })
          .then((res) => {
            this.reportTypeList = res.data;
          });
      },
      immediate: true,
    },
  },
  created() {
    this.innerDialogFormVisible = this.dialogFormVisible;
    if (this.dialogFormVisible) {
      this.init();
    }
    this.workFlowList();
  },
  methods: {
    ckChange() {
      this.show = false;
      this.$nextTick(() => {
        this.show = true;
      });
    },
    async init() {
      // editId 存在表示编辑 不存在表示新增
      this.title = !this.editId
        ? this.$t("ModuleSysBusiness.OperateType.add")
        : this.readonly
          ? this.$t("ModuleSysBusiness.OperateType.view")
          : this.$t("ModuleSysBusiness.OperateType.redact");

      // 编号类型
      getDictList({ dictCode: "ReportNumType" }).then((res) => {
        this.reportNumTypeOptions = res.data;
      });

      // 查询一级样品类别
      SampleCategoryParentGetList({}).then((res) => {
        this.sampleCategoryOptions = res.data;
      });

      // 编辑
      if (this.editId) {
        // 获取用户信息
        get({ id: this.editId })
          .then((res) => {
            const data = res.data;
            data.attachmentTemplate = data.attachmentTemplate = [
              {
                name: data.attachmentName || "",
                url:
                  data.protocol +
                  data.fileBucket +
                  "/" +
                  data.fileDomain +
                  "/" +
                  data.attachmentTemplate,
                url2: data.attachmentTemplate,
              },
            ];
            this.formData = data;
            this.formData.scopeList = data.scope.split(",");
          })
          .catch(() => {});
      }
    },
    workFlowList() {
      GetUserGroupList({ pageIndex: 1, pageSize: 999 }).then((res) => {
        this.groupList = res.data.dataList;
      });
      GetWorkFlowDetailList({ workFlowKey: "ReportVerify" }).then((res) => {
        this.tableData = res.data;
      });
    },
    closeDialog() {
      this.$parent.getList();
      this.innerDialogFormVisible = false;
      this.$emit("update:dialogFormVisible", false);
      this.$emit("update:editId", "");
    },
    onSubmit: _.throttle(function() {
      if (this.submitLoad) {
        this.submitLoad = false;
        this.$refs.formData.validate((valid) => {
          if (valid) {
            this.loading = true;
            this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
            const requestData = JSON.parse(JSON.stringify(this.formData));
            requestData.attachmentTemplate = "";
            requestData.attachmentName = "";
            requestData.scope = requestData.scopeList.join(",");
            if (
              this.formData.attachmentTemplate !== null &&
              this.formData.attachmentTemplate.length !== 0
            ) {
              requestData.attachmentTemplate =
                this.formData.attachmentTemplate[0].url2;
              requestData.attachmentName =
                this.formData.attachmentTemplate[0].name;
            }

            if (this.formData.id <= 0) {
              this.addAPI(requestData);
            } else {
              this.editAPI(requestData);
            }
          } else {
            this.submitLoad = true;
            return false;
          }
        });
      }
    }, 2000),
    // 新增接口
    addAPI(data) {
      create(data)
        .then((res) => {
          if (res.code === 200) {
            this.submitLoad = true;

            this.closeDialog();
          } else {
            this.submitLoad = true;

            this.showValidateMsgCheck(res);
          }
          this.loading = false;
        })
        .catch(() => {
          this.submitLoad = true;

          this.loading = false;
        });
    },
    // 编辑接口
    editAPI(data) {
      update(data)
        .then((res) => {
          if (res.code === 200) {
            this.submitLoad = true;

            this.closeDialog();
          } else {
            this.submitLoad = true;

            this.showValidateMsgCheck(res);
          }
          this.loading = false;
        })
        .catch(() => {
          this.submitLoad = true;

          this.loading = false;
        });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("name", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("introduction", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("tpye", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("scopeList", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "attachmentTemplate",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("creator", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("updater", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
